package com.zyd.blog.homeart.service.impl;

import com.zyd.blog.homeart.service.IDesignArticleService;
import com.zyd.blog.persistence.beans.*;
import com.zyd.blog.persistence.beans.es.EsDesignArticle;
import com.zyd.blog.persistence.mapper.*;
import me.zhyd.oauth.utils.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liusongqi
 * @since 2020-02-10
 */
@Service
class DesignArticleServiceImpl implements IDesignArticleService {
    @Autowired
    private DesignArticleMapper designArticleMapper;
    @Autowired
    private DictionariesMapper dictionariesMapper;
    @Autowired
    private MyParticipateMapper myParticipateMapper;
    @Autowired
    private CenterMapper centerMapper;
    @Autowired
    private FineArtMapper fineArtMapper;
    @Autowired
    private CommentRelationMapper commentRelationMapper;
    @Autowired
    private DesignArticleEditMapper designArticleEditMapper;
    @Autowired
    private SoftProductMapper softProductMapper;
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private CommentReplyMapper commentReplyMapper;

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Map<String, Object> soft(String userId, int page, int count) {
        DesignArticle designArticle = new DesignArticle();
        designArticle.setTop("0");
        int i = designArticleMapper.selectCount(designArticle);
        List<CenterNew> soft = designArticleMapper.soft(userId,  count * page - count, count);
        assert soft != null;
        for (CenterNew center : soft) {
            center.setDesignStyle(dictionariesMapper.content(center.getDesignStyle()));
            center.setDesignApartment(dictionariesMapper.content(center.getDesignApartment()));
            center.setDesignPlace(dictionariesMapper.content(center.getDesignPlace()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", soft);
        int i1 = designArticleMapper.selectCount(null);
        //hasmore 1有下一页   0 没有 判断页数和条数  相乘 是否小于 总条数 以此判断 是否有下一页
        if (page * count <= i1) {
            map.put("hasMore", 1);
        } else {
            map.put("hasMore", 0);
        }
        return map;
    }

    @Override
    public Map<String, Object> searchDesign(String value,String userId, int page, int count) {
        List<CenterNew> soft = designArticleMapper.searchDesign(value,userId, count * page - count, count );
        for (CenterNew center : soft) {
            center.setDesignStyle(dictionariesMapper.content(center.getDesignStyle()));
            center.setDesignApartment(dictionariesMapper.content(center.getDesignApartment()));
            center.setDesignPlace(dictionariesMapper.content(center.getDesignPlace()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", soft);
        int i1 = designArticleMapper.searchCountAll(value);
        //hasmore 1有下一页   0 没有 判断页数和条数  相乘 是否小于 总条数 以此判断 是否有下一页
        if (page * count <= i1) {
            map.put("hasMore", 1);
        } else {
            map.put("hasMore", 0);
        }
        return map;
    }

    @Override
    public Map<String, Object> personalSoft(String userId, int page, int count,String style) {
        List<CenterNew> soft = designArticleMapper.personalSoft(userId, count * page - count, count ,style);
        for (CenterNew center : soft) {
            center.setDesignStyle(dictionariesMapper.content(center.getDesignStyle()));
            center.setDesignApartment(dictionariesMapper.content(center.getDesignApartment()));
            center.setDesignPlace(dictionariesMapper.content(center.getDesignPlace()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", soft);
        int i1 = designArticleMapper.selectCount(null);
        //hasmore 1有下一页   0 没有 判断页数和条数  相乘 是否小于 总条数 以此判断 是否有下一页
        if (page * count <= i1) {
            map.put("hasMore", 1);
        } else {
            map.put("hasMore", 0);
        }
        return map;
    }

    @Override
    public Map<String, Object> personalSoftOrder(String userId, int page, int count, String style, String coverUserId) {
        List<CenterNew> soft = designArticleMapper.personalSoftOrder(userId,  count * page - count, count ,style,coverUserId);
        for (CenterNew center : soft) {
            center.setDesignStyle(dictionariesMapper.content(center.getDesignStyle()));
            center.setDesignApartment(dictionariesMapper.content(center.getDesignApartment()));
            center.setDesignPlace(dictionariesMapper.content(center.getDesignPlace()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", soft);
        int i1 = designArticleMapper.selectCount(null);
        //hasmore 1有下一页   0 没有 判断页数和条数  相乘 是否小于 总条数 以此判断 是否有下一页
        if (page * count <= i1) {
            map.put("hasMore", 1);
        } else {
            map.put("hasMore", 0);
        }
        return map;
    }

    @Override
    public Map<String, Object> sort(String region, String sort, String style, String province, String city, String area, String userId, String place, int page, int count) throws Exception {
        List<CenterNew> sort1 = designArticleMapper.sort(region, sort, style, province, city, area, userId, place,  count * page - count, count );
        for (CenterNew center : sort1) {
            center.setDesignStyle(dictionariesMapper.content(center.getDesignStyle()));
            center.setDesignApartment(dictionariesMapper.content(center.getDesignApartment()));
            center.setDesignPlace(dictionariesMapper.content(center.getDesignPlace()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list", sort1);
        int i1 = designArticleMapper.count(region, sort, style, province, city, area, userId, place);
        //hasmore 1有下一页   0 没有 判断页数和条数  相乘 是否小于 总条数 以此判断 是否有下一页
        if (page * count <= i1) {
            map.put("hasMore", 1);
        } else {
            map.put("hasMore", 0);
        }
        return map;
    }

    //state 0收藏 1点赞 2评论 3分享
    @Override
    public Integer fabulous(String id, String userId, String category, String state) throws Exception {
        Integer fabulous = 0;
        MyParticipate myParticipate = new MyParticipate();
        myParticipate.setAddTime(sdf.format(System.currentTimeMillis()));
        myParticipate.setUserId(userId);
        myParticipate.setState(state);
        myParticipate.setArticleId(id);
        myParticipate.setCategory(category);
        myParticipate.setParticipateId(UuidUtils.getUUID());
        if (state.equals("3")){
            Integer fenxaing = myParticipateMapper.fenxaing(id);
            if (fenxaing==0){
                try {
                    myParticipateMapper.insert(myParticipate);
                } catch (Exception e) {
                    throw new Exception("添加到我的参与失败");
                }
            }
        }else{
            try {
                myParticipateMapper.insert(myParticipate);
            } catch (Exception e) {
                throw new Exception("添加到我的参与失败");
            }
            //查询该用户的 该篇文章 是否为第一次 点赞 评论 收藏
            Integer integer = centerMapper.centerCount(id, userId);
            if (integer == 0) {
                try {
                    insert(userId, id, state);
                } catch (Exception e) {
                    throw new Exception("添加center失败");
                }
            } else if (integer == 1) {
                try {
                    update(userId, id, state);
                } catch (Exception e) {
                    throw new Exception("修改center失败");
                }
            }
            if (state.equals("0")) {
                try {
                    fabulous = designArticleMapper.addCollection(id);
                } catch (Exception e) {
                    throw new Exception("收藏失败");
                }

            } else if (state.equals("1")) {
                try {
                    fabulous = designArticleMapper.fabulous(id);
                } catch (Exception e) {
                    throw new Exception("点赞失败");
                }
            }
        }


        return fabulous;
    }

    @Override
    public Integer addArticle(DesignArticle designArticle) throws Exception {
        int insert;
        designArticle.setDesignId(UuidUtils.getUUID());
        designArticle.setAddTime(sdf.format(System.currentTimeMillis()));
        designArticle.setUpdateTime(sdf.format(System.currentTimeMillis()));
        designArticle.setZanNumber(0);
        designArticle.setCollectionNumber(0);
        designArticle.setDiscussNumber(0);
        designArticle.setTopTime(sdf.format(System.currentTimeMillis()));
        designArticle.setUseState("0");
        //是否审核通过0通过1未通过2审核中
        designArticle.setExamine("2");
        designArticle.setDeleteState("1");
        designArticle.setTop("1");
        designArticle.setUserName("用户名");
        designArticle.setUserImage("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2932779449,831692746&fm=26&gp=0.jpg");
        designArticle.setProvince("广东省");
        designArticle.setCity("深圳市");
        designArticle.setArea("南山区");
        designArticle.setEdit("1");
        designArticle.setNum(0);
        designArticle.setUseState("0");
        try {
            insert = designArticleMapper.insert(designArticle);
        } catch (Exception e) {
            throw new Exception("发布文章失败");
        }
        return insert;
    }

    @Override
    public Integer addArticleEdit(DesignArticleEdit designArticleEdit) throws Exception {
        int insert;
        designArticleEdit.setAddTime(sdf.format(System.currentTimeMillis()));
        designArticleEdit.setUpdateTime(sdf.format(System.currentTimeMillis()));
        designArticleEdit.setZanNumber(0);
        designArticleEdit.setCollectionNumber(0);
        designArticleEdit.setDiscussNumber(0);
        designArticleEdit.setTopTime(sdf.format(System.currentTimeMillis()));
        //是否审核通过0通过1未通过2审核中
        designArticleEdit.setExamine("2");
        designArticleEdit.setDeleteState("1");
        designArticleEdit.setTop("1");
        designArticleEdit.setUserName("用户名");
        designArticleEdit.setUserImage("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2932779449,831692746&fm=26&gp=0.jpg");
        designArticleEdit.setProvince("广东省");
        designArticleEdit.setCity("深圳市");
        designArticleEdit.setArea("南山区");
        designArticleEdit.setEdit("0");
        try {
            insert = designArticleEditMapper.insert(designArticleEdit);
        } catch (Exception e) {
            throw new Exception("添加到edit失败");
        }
        try {
            designArticleMapper.updateEdit(designArticleEdit.getDesignId());
        } catch (Exception e) {
            throw new Exception("主表状态变为2失败");
        }
        return insert;
    }

    //state 0收藏 1点赞 2评论 3分享
    @Override
    public Integer reduceZan(String id, String userId, String category, String state) throws Exception {
        Integer reduceZan = 0;
        MyParticipate myParticipate = new MyParticipate();
        myParticipate.setState(state);
        myParticipate.setArticleId(id);
        myParticipate.setUserId(userId);
        myParticipate.setCategory(category);
        int delete;
        try {
            delete = myParticipateMapper.delete(myParticipate);
        } catch (Exception e) {
            throw new Exception("我的参与点赞删除失败");
        }

        try {
            cancel(userId, id, state);
        } catch (Exception e) {
            throw new Exception("修改取消 center失败");
        }

        if (state.equals("0")) {
            try {
                reduceZan = designArticleMapper.deleteCollection(id);
            } catch (Exception e) {
                throw new Exception("取消收藏失败");
            }
        } else if (state.equals("1")) {
            try {
                reduceZan = designArticleMapper.reduceZan(id);
            } catch (Exception e) {
                throw new Exception("取消点赞失败");
            }
        }
        return reduceZan + delete;
    }

    @Override
    public Map<String, Object> specific(String designId, String userId, String designStyle, String designPlace) throws Exception {
        Map<String, Object> map = new HashMap<>();
        try {
            CenterNew specific = designArticleMapper.specific(designId, userId);
            specific.setDesignStyle(dictionariesMapper.content(specific.getDesignStyle()));
            specific.setDesignApartment(dictionariesMapper.content(specific.getDesignApartment()));
            specific.setDesignPlace(dictionariesMapper.content(specific.getDesignPlace()));
            map.put("specific", specific);
        } catch (Exception e) {
            throw new Exception("获取内容失败");
        }
        List<DesignArticle> designArticles;
        try {
            designArticles = designArticleMapper.recommendArticle(dictionariesMapper.id(designStyle), dictionariesMapper.id(designPlace), designId);
            for (int i = 0; i < designArticles.size(); i++) {
                designArticles.get(i).setDesignStyle(dictionariesMapper.content(designArticles.get(i).getDesignStyle()));
                designArticles.get(i).setDesignApartment(dictionariesMapper.content(designArticles.get(i).getDesignApartment()));
                designArticles.get(i).setDesignPlace(dictionariesMapper.content(designArticles.get(i).getDesignPlace()));
            }
            map.put("designArticles", designArticles);
        } catch (Exception e) {
            throw new Exception("获取失败");
        }

        return map;
    }

    @Override
    public List<EsDesignArticle> getEsDesignArticle(int page, int limit) {
        return designArticleMapper.getEsDesignArticle((page - 1) * limit, limit);
    }

    @Override
    public List<DesignArticle> recommendArticle(String designStyle, String designPlace) throws Exception {
        List<DesignArticle> designArticles;
        try {
            //designArticles = designArticleMapper.recommendArticle(designStyle, designPlace);
        } catch (Exception e) {
            throw new Exception("获取失败");
        }
        return null;
    }

    @Override
    public Integer updateDraft(String designId, String userId) throws Exception {
        Integer integer;
        try {
            integer = designArticleMapper.updateDraft(designId, userId, "0");
        } catch (Exception e) {
            throw new Exception("修改状态失败");
        }
        return integer;
    }

    @Override
    public Integer editDraft(String designId, String userId) throws Exception {
        Integer integer;
        try {
            integer = designArticleMapper.updateDraft(designId, userId, "1");
        } catch (Exception e) {
            throw new Exception("修改状态失败");
        }
        return integer;
    }

    @Override
    public Map<String, Object> myAdd(String userId, int page, int count) throws Exception {
        List<CenterNew> designArticles;
        Map<String, Object> map = new HashMap<>();
        try {
            designArticles = designArticleMapper.myAdd(userId, page * count - count, count);
            for (CenterNew article : designArticles) {
                article.setDesignStyle(dictionariesMapper.content(article.getDesignStyle()));
                article.setDesignApartment(dictionariesMapper.content(article.getDesignApartment()));
                article.setDesignPlace(dictionariesMapper.content(article.getDesignPlace()));
            }
            DesignArticle designArticle = new DesignArticle();
            designArticle.setUserId(userId);
            int integer = designArticleMapper.selectCount(designArticle);
            map.put("list", designArticles);
            if (page * count <= integer) {
                map.put("hasMore", 1);
            } else {
                map.put("hasMore", 0);
            }
        } catch (Exception e) {
            throw new Exception("获取失败");
        }
        return map;
    }

    @Override
    public Map<String, Object> index(String userId) {
        DesignArticle designArticle = new DesignArticle();
        int page = 1;
        int count = Integer.parseInt(dictionariesMapper.num());
        designArticle.setTop("0");
        int i = designArticleMapper.selectCount(designArticle);
        List<CenterNew> soft = designArticleMapper.soft(userId,  count * page - count, count );
        for (CenterNew center : soft) {
            center.setDesignStyle(dictionariesMapper.content(center.getDesignStyle()));
            center.setDesignApartment(dictionariesMapper.content(center.getDesignApartment()));
            center.setDesignPlace(dictionariesMapper.content(center.getDesignPlace()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("design", soft);
        FineArt fineArt = new FineArt();
        fineArt.setTop("0");
        int i2 = fineArtMapper.selectCount(fineArt);
        List<FineArtNew> FineArtNew = fineArtMapper.soft(userId, count * page - count, count );
        map.put("FineArt", FineArtNew);
        SoftProduct softProduct = new SoftProduct();
        softProduct.setTop("0");
        int i3 = softProductMapper.selectCount(softProduct);
        List<SoftNew> soft2=softProductMapper.soft(userId,count*page-count,count);
        assert soft2 != null;
        for (SoftNew center : soft2) {
            center.setSoftStyle(dictionariesMapper.content(center.getSoftStyle()));
            center.setSoftApartment(dictionariesMapper.content(center.getSoftApartment()));
            center.setSoftPlace(dictionariesMapper.content(center.getSoftPlace()));
        }
        map.put("softProduct", soft2);
        return map;
    }

    @Override
    public DesignArticle bianji(String id) {
        DesignArticle designArticle = new DesignArticle();
        designArticle.setDesignId(id);
        return designArticleMapper.selectOne(designArticle);
    }

    @Override
    public Integer delete(String id,String state) throws Exception {
        if (state.equals("0")){
            //根据文章id找到评论id  放到list
            List<CommentId> commentIds = commentMapper.commentAll(id);
            for (CommentId commentId : commentIds) {
                try {
                    commentMapper.deleteComment(commentId.getCommentId());
                } catch (Exception e) {
                    throw new Exception("删除评论失败");
                }
                try {
                    commentRelationMapper.deleteCommentRelation(commentId.getCommentId());
                } catch (Exception e) {
                    throw new Exception("删除comment_relation失败");
                }
                try {
                    commentMapper.deleteCommentReply(commentId.getCommentId());
                } catch (Exception e) {
                    throw new Exception("删除评论回复失败");
                }
            }
            try {
                centerMapper.deleteCenter(id);
            } catch (Exception e) {
                throw new Exception("删除center失败！");
            }
            try {
                myParticipateMapper.deleteArticle(id);
            } catch (Exception e) {
                throw new Exception("从我的参与中删除失败");
            }
        }

        try {
            designArticleMapper.deleteArticle(id);

        } catch (Exception e) {
            throw new Exception("删除文章失败");
        }
        return null;
    }

    @Override
    public Integer update(DesignArticle designArticle) {
        Integer integer;
        if (designArticle.getExamine().equals("1")) {
            integer = designArticleMapper.updateOne(designArticle.getDesignId(), designArticle.getDesignTitle(), designArticle.getCoverImage(),
                    designArticle.getDesignStyle(), designArticle.getDesignApartment(), designArticle.getDesignPlace(),
                    designArticle.getDesignContent(), sdf.format(System.currentTimeMillis()), designArticle.getAreaNumber(),
                    designArticle.getDraft(), designArticle.getIntroduce(), designArticle.getPlaceContent(), designArticle.getApartmentContent(),
                    designArticle.getStyleContent(), sdf.format(System.currentTimeMillis()), "2");
        } else {
            integer = designArticleMapper.updateOne(designArticle.getDesignId(), designArticle.getDesignTitle(), designArticle.getCoverImage(),
                    designArticle.getDesignStyle(), designArticle.getDesignApartment(), designArticle.getDesignPlace(),
                    designArticle.getDesignContent(), sdf.format(System.currentTimeMillis()), designArticle.getAreaNumber(),
                    designArticle.getDraft(), designArticle.getIntroduce(), designArticle.getPlaceContent(), designArticle.getApartmentContent(),
                    designArticle.getStyleContent(), sdf.format(System.currentTimeMillis()), designArticle.getExamine());
        }
        return integer;
    }

    @Override
    public Integer tongguole(String id) throws Exception {
            //根据文章id找到评论id  放到list
            List<CommentId> commentIds = commentMapper.commentAll(id);
            for (CommentId commentId : commentIds) {
                try {
                    commentMapper.deleteComment(commentId.getCommentId());
                } catch (Exception e) {
                    throw new Exception("删除评论失败");
                }
                try {
                    commentRelationMapper.deleteCommentRelation(commentId.getCommentId());
                } catch (Exception e) {
                    throw new Exception("删除comment_relation失败");
                }
                try {
                    commentMapper.deleteCommentReply(commentId.getCommentId());
                } catch (Exception e) {
                    throw new Exception("删除评论回复失败");
                }
            }
            try {
                centerMapper.deleteCenter(id);
            } catch (Exception e) {
                throw new Exception("删除center失败！");
            }
            try {
                myParticipateMapper.deleteArticle(id);
            } catch (Exception e) {
                throw new Exception("从我的参与中删除失败");
            }

        try {
            designArticleMapper.deleteArticle(id);
        } catch (Exception e) {
            throw new Exception("删除文章失败");
        }
        DesignArticle des = designArticleEditMapper.des(id);
        des.setDesignId(UuidUtils.getUUID());
        des.setEdit("1");
        des.setExamine("0");
        des.setAddTime(sdf.format(System.currentTimeMillis()));
        designArticleMapper.insert(des);
        designArticleEditMapper.deleteEdit(id);
        return null;
    }

    @Override
    public List<Interest> interestAll() {
        return designArticleMapper.interestAll();
    }

    @Override
    public Integer stopUser(String userId) {
        List<Comment> comments = commentMapper.stopUserAll(userId);
        for (Comment comment : comments) {
            if (comment.getState().equals("1")) {
                designArticleMapper.commentReduce(comment.getAnswerId());
            } else if (comment.getState().equals("3")) {
                fineArtMapper.commentReduce(comment.getAnswerId());
            }
        }
        designArticleMapper.stopUser(userId);
        fineArtMapper.stopUser(userId);
        commentMapper.stopUser(userId);
        commentReplyMapper.stopUser(userId);
        return null;
    }

    @Override
    public Integer passUser(String userId) {
        List<Comment> comments = commentMapper.stopUserAll(userId);
        for (Comment comment : comments) {
            if (comment.getState().equals("1")) {
                designArticleMapper.commentNum(comment.getAnswerId());
            } else if (comment.getState().equals("3")) {
                fineArtMapper.commentNum(comment.getAnswerId());
            }
        }
        designArticleMapper.passUser(userId);
        fineArtMapper.passUser(userId);
        commentMapper.passUser(userId);
        commentReplyMapper.passUser(userId);
        return null;
    }

    //0收藏 1点赞 2评论 3分享 b
    private void insert(String userId, String id, String state) {
        Center center = new Center();
        center.setArticleId(id);
        center.setUserId(userId);
        switch (state) {
            case "0":
                center.setCollection("0");
                center.setZan("1");
                center.setDiscuss("1");
                break;
            case "1":
                center.setZan("0");
                center.setDiscuss("1");
                center.setCollection("1");
                break;
            case "2":
                center.setDiscuss("0");
                center.setZan("1");
                center.setCollection("1");
                break;
        }

        centerMapper.insert(center);
    }

    //0收藏 1点赞 2评论 3分享
    private void update(String userId, String id, String state) {
        centerMapper.update(userId, id, state);
    }

    private void cancel(String userId, String id, String state) {
        centerMapper.cancel(userId, id, state);
    }

    //定时任务 处理草稿箱
    @Scheduled(cron = "0 0 0 * * ?")
    public void timerToNow() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime minus = now.minus(30, ChronoUnit.DAYS);
        LocalDate localDate = minus.toLocalDate();
        designArticleMapper.deleteCaoGao(localDate.toString());
        System.out.println("定时任务 now time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

}
